import {
    CallHandler,
    ClassSerializerContextOptions,
    ClassSerializerInterceptor,
    ExecutionContext,
    Injectable,
    PlainLiteralObject,
    StreamableFile,
} from '@nestjs/common';
import { isArray, isObject } from 'lodash';
import { map } from 'rxjs';

@Injectable()
export class AppInterceptor extends ClassSerializerInterceptor {
    // intercept(context: ExecutionContext, next: CallHandler) {
    //     const response = context.switchToHttp().getResponse();

    //     // 设置 HTTP 状态码为 200
    //     response.status(200);

    //     return next.handle().pipe(
    //         map((data) => this.serialize(data, this.getContextOptions(context))), // 调用自定义的序列化逻辑
    //     );
    // }
    serialize(
        response: PlainLiteralObject | Array<PlainLiteralObject>,
        options: ClassSerializerContextOptions,
    ): PlainLiteralObject | Array<PlainLiteralObject> {
        let result;
        if ((!isObject(response) && !isArray(response)) || response instanceof StreamableFile) {
            result = response;
        }

        if (isArray(response)) {
            result = (response as PlainLiteralObject[]).map((item) =>
                isObject(item) ? this.transformToPlain(item, options) : item,
            );
        } else {
            result = this.transformToPlain(response, options);
        }

        return {
            code: 200,
            message: 'success',
            data: result,
        };
    }
}
